<?php

namespace app\api\controller;

use app\common\controller\Api;

use app\common\model\drug\Keyword as DrugKeyword;
use app\common\model\drug\component\Keyword as DrugComponentKeyword;
use app\common\model\drug\Drugs as DrugDrugs;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }


    public function search($keyword, $page = 1)
    {
        $showapi_appid = config('site.showapi_appid');
        $showapi_sign = config("site.showapi_secret");

        $limit = 30;
        $url = "https://route.showapi.com/93-97?showapi_appid={$showapi_appid}&showapi_sign={$showapi_sign}";

        $data = [
            'keyword' => $keyword,
            'page' => $page,
            'limit' => $limit,
        ];

        $res = $this->httpPost($url, $data);

        $data = ['page' => $page, 'list' => [], 'total_page' => 0];
        if ($res['showapi_res_code'] == 0 && empty($res['showapi_res_error']) && !empty($res['showapi_res_body']['drugList'])) {

            $data['page'] = $res['showapi_res_body']['page'];

            $list = DrugDrugs::where("status = 'normal' AND (title = '".$keyword."' OR alias_title = '".$keyword."')")->select();

            foreach($list as $k=>$v){
                $similarOne =  similar_text($keyword,$v['title']);

                $similarTwo =  similar_text($keyword,$v['alias_title']);

                $list[$k]['similar'] = $similarOne >= $similarTwo ? $similarOne : $similarTwo;
                $list[$k]['usage'] = $v['usage_dosage'];
                $list[$k]['title'] = $similarOne >= $similarTwo ? $v['title'] : $v['alias_title'];
            }
            foreach ($res['showapi_res_body']['drugList'] as $key => $k) {
                if (!empty($k['zycf'])) {
                    $item = [
                        'title' => $k['drugName'],
						'company'=>$k['manu'],
                        'primary_disease' => isset($k['zzjb']) ? $k['zzjb'] : '无', // 主治疾病
                        'announcements' => isset($k['zysx']) ? $k['zysx'] : '无' , // 注意事项
                        'main_components' => isset($k['zycf']) ? $k['zycf'] : '无', // 主要成分
                        'usage' => isset($k['yfyl']) ? $k['yfyl'] : '无', // 用法用量
						'logo'=>$k['imgUrl'] ? $k['imgUrl'] : cdnurl(config('site.default_goods_logo'), true),
                     'similar'=>$keyword === $k['drugName'] ? 100 : similar_text($keyword,$k['drugName'])
                    ];
                    array_push($list, $item);
                }
            }

            usort($list, function($a, $b) {
                if($b['similar'] && $a['similar']){
                    return $b['similar'] - $a['similar'];
                }
            });


            $data['list'] = $list;
            $data['total_page'] = ceil($res['showapi_res_body']['allResults'] / $limit);

            $this->success('返回成功', $data);
        } else {
            $this->error($res['showapi_res_error']);
        }
    }


    public function checkcomponent($name, $zycf)
    {
        $data = [];
        $drugKeyword = DrugKeyword::where(['status' => 'normal'])->field(['title', 'alias_title'])->select();
        foreach ($drugKeyword as $key => $k) {
            if (strpos($name, $k['title']) !== false) {
                $data[] = !empty($k['alias_title']) ? $k['alias_title'] : $k['title'];
            }
        }

        $drugComponentKeyword = DrugComponentKeyword::where(['status' => 'normal'])->field(['title', 'alias_title'])->select();
        foreach ($drugComponentKeyword as $key => $k) {
            if (strpos($zycf, $k['title']) !== false) {
                $data[] = !empty($k['alias_title']) ? $k['alias_title'] : $k['title'];
            }
        }
        $this->success('返回成功', $data);
    }


    private function httpPost($url, $data)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            return 'Error POST' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return json_decode($result, true); // 返回数据
    }
}
